/* eslint-disable */
import axios from 'axios'
import { ElMessage } from 'element-plus'
class Request {
  http = axios
  constructor ({baseURL='', timeout = 10000, headers = {}}) {
    this.http = axios.create({
      baseURL,
      withCredentials: false,
      timeout,
      headers,
    })
    // 添加请求拦截器
    this.http.interceptors.request.use((config) => {
      // 在发送请求之前做些什么
      let {headers, data = {}, params = {}} = config
      if (config.url !== '/file/upload') {
        data = {
          ...data,
        }
        Object.keys(data).forEach(key => data && (typeof data[key] === 'undefined') && delete data[key])
      }
      config.data = data
      params = {
        ...params,
      }
      config.params = params
      Object.keys(params).forEach(key => params && (typeof params[key] === 'undefined') && delete params[key])
      headers['Access-Control-Allow-Origin'] = '*'
      config.headers = headers
      return config
    }, error =>{
      // 对请求错误做些什么
      Promise.reject(error)
    })

    // 添加响应拦截器
    this.http.interceptors.response.use(response => {
      if (response.status === 200) { 
        return response.data.resultContent
      }
      // 对响应数据做点什么
      switch (response.data.code) {
        case 200:
          return response.data
        case 401:
          if(document.getElementsByClassName('el-message').length > 0) return
          location.replace(location.origin+'/#/login')
      }
      if (response.data.errno === 0) {
        return response.data
      }
      const detailMessage = response.data.message || '服务器开小差了，稍后再试试'
      ElMessage.error(detailMessage)
      return Promise.reject({...response.data, detailMessage})
    }, error => {
      // 对响应错误做点什么
      console.error('网络异常:', error)
      if(document.getElementsByClassName('el-message').length > 0) return
      ElMessage.error('网络异常')
      location.replace(location.origin+'/#/login')
      return Promise.reject({detailMessage: '网络出现了异常，稍后再试试'})
    })
  }

  fetch ({
    method = 'get',
    headers = {},
    url = '',
    params,
    data,
  }) {
    return this.http({
      method,
      headers,
      url,
      params,
      data,
    })
  }

  get (url, params = {}, headers) {
    console.log(url)
    return this.fetch({
      url,
      params,
      headers,
    })
  }

  post (url, data = {}, headers) {
    return this.fetch({
      method: 'POST',
      url,
      data,
      headers,
    })
  }

  upload (url, data = {}, headers) {
    return this.fetch({
      method: 'POST',
      url,
      data,
      headers: {
        ...headers,
        'Content-Type': 'multipart/form-data',
      },
    })
  }
}

export default Request
